/**
 * 渲染器封装 - L5
 * @author lonphy
 * @version 0.1
 */
(function(L5) {
	"use strict";

	function initConstructor() {
		L5.Render = function(canvas) {
			this.scenes = null;
			this.stop = false;
			this.lastRenderTime = 0;
			this.gl = canvas.getContext('webgl', {antialias:true});
			this.width = canvas.width;
			this.height = canvas.height;

			this.output = null;
		};
	}
	function initMethods() {
		let $fn = L5.Render.prototype;
		/**
		 * 初始化设备环境
		 * @param options
		 */
		$fn.init = function(options) {
			options = options || {};
			this.output = options.output || {};

			for (let item in this.output) {
				if (this.output.hasOwnProperty(item)) {
					let node = document.createTextNode('');
					this.output[item].appendChild(node);
					this.output[item] = node;
				}
			}

			let gl = this.gl;
			this.blend = options.blend || false;
			let c = new L5.Vec4(options.clear);
			gl.clearColor(c.r, c.g, c.b, c.a);
			gl.viewport(0, 0, this.width, this.height);

			//gl.cullFace(gl.FRONT_AND_BACK);
			//gl.frontFace(gl.CCW);
			//gl.disable(gl.CULL_FACE);
			if (options.blend) {
				gl.enable( gl.BLEND );			// 开启混合
				gl.disable( gl.DEPTH_TEST );		// 关闭深度测试
				gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
			}else{
				gl.enable( gl.DEPTH_TEST );
				gl.depthFunc(gl.LEQUAL);	 // 远处的物体模糊
				gl.clearDepth(1.0);				// 清除所有
			}
		};
		/**
		 * 开始渲染
		 * @param s {L5.Scenes}
		 */
		$fn.render = function(s) {
			this.scenes = s;
			s.drawor = this;
			let $this = this;
			let frameHandler = function(time) {
				if ($this.scenes !== null && !$this.stop) {
					window.requestAnimationFrame(frameHandler);
					let fps = 1000 / (time - $this.lastRenderTime);
					if ($this.output.fps) {
						$this.output.fps.nodeValue = fps|0;
					}
					$this.lastRenderTime = time;
					$this.scenes.render($this.gl, fps, time);
				}
			};
			window.requestAnimationFrame(frameHandler);
		};
		$fn.stopRender = function() {
			this.stop = true;
		};
	}
	initConstructor();
	initMethods();
})(window.L5);